import { fromEvent, of, from, Observable } from "rxjs";
import { debounceTime, distinctUntilChanged, filter, map, switchMap, tap } from "rxjs/operators";
import axios from "axios";
import { GithubUser, GithubUserResult } from "./typings";
import * as _ from "lodash";
import * as Dayjs from "dayjs";

const input = document.createElement("input");
input.placeholder = "Search";
input.autocomplete = "off";
input.type = "text";
document.body.appendChild(input);

const progress = document.createElement("div");
document.body.appendChild(progress);

const container = document.createElement("div");
container.style.marginTop = "40px";
document.body.appendChild(container);

function displayResult(users: string[]) {
    Array.from(container.childNodes).forEach(n => n.parentElement.removeChild(n));
    const m = document.createElement("div");
    m.innerHTML = `results refreshed at ${Dayjs().format("HH:mm:ss")}`
    m.style.color = "blue";
    container.appendChild(m);

    const ul = document.createElement("div");
    for (const user of users) {
        const li = document.createElement("div");
        li.innerText = user;
        ul.appendChild(li);
    }
    container.appendChild(ul);
}

const source$: Observable<string> = fromEvent(input, "input").pipe(map(e => {
    const target = e.target as HTMLInputElement;
    return target.value;
}));

const MIN_Q_LEN = 3;
function autocompleteGithubUsers(q: string): Observable<GithubUser[]> {
    if (!q) throw new Error("q must not be falsy");
    const HOST = "https://api.github.com";
    const githubPrivateToken = "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";
    const p: Promise<GithubUserResult> = axios.get(HOST + `/search/users?q=${encodeURIComponent(q)}`, {
        headers: {
            'Accept': 'application/json',
            'Authorization': 'Basic ' + btoa('foresightyj:' + githubPrivateToken)
        }
    }).then(res => res.data);
    return from(p).pipe(map(r => r.items));
}
source$.pipe(
    // filter(q => q.length >= MIN_Q_LEN),
    debounceTime(250),
    distinctUntilChanged(),
    tap(v => console.log('after distinct', v)),
    tap(v => progress.innerText = "..."),
    switchMap(q => {
        if (q.length < MIN_Q_LEN) {
            return of([]);
        }
        return autocompleteGithubUsers(q);
    }),
    tap(v => progress.innerHTML = "&nbsp;"),
).subscribe(users => {
    displayResult(_.take(users.map(i => i.login), 10));
});


